package com.yyfax.ph.common.scan.bankcard.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.OrientationEventListener;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.yyfax.common.CLog;
import com.yyfax.ph.R;
import exocr.bankcard.EXBankCardInfo;
import exocr.exocrengine.DictManager;

import java.io.IOException;

/**
 * 项目名称：YYlengding
 * 类描述：
 * 创建人：xiongyufeng
 * 创建时间：2016/11/3 15:47
 * 修改人：xiongyufeng
 * 修改时间：2016/11/3 15:47
 * 修改备注：
 */
public class CardRecoActivity extends AppCompatActivity implements GetBankCardListener {
	private static final String TAG = CardRecoActivity.class.getSimpleName();

	public static final int msg_scan_bank_card = 0x11;
	public static final String bank_card_number_flag = "bank_card_number_flag";

	@BindView(R.id.bankcard_scan_surface_view)
	SurfaceView mSurfaceView;
	@BindView(R.id.bankcard_scan_overlay_view)
	OverlayView mOverlay;
	@BindView(R.id.bankcard_scan_back_tv)
	TextView mBankcardScanBackTv;

	private boolean bCamera = true;
	private boolean bPhotoReco;

	private MediaPlayer mediaPlayer;
	private boolean playMusicFlag = true;
	private boolean vibrateFlag = true;

	private static final int DEGREE_DELTA = 15;
	private static final int ORIENTATION_PORTRAIT = 1;
	private final static int ORIENTATION_LANDSCAPE = 2;
	private static final int ORIENTATION_LANDSCAPE_RIGHT = 3;
	private static final int ORIENTATION_LANDSCAPE_LEFT = 4;
	private int mFrameOrientation;
	private int mLastDegrees;
	private Rect mGuideFrame;
	private CardScanner mCardScanner;
	private OrientationEventListener orientationListener;

	public static void start(Activity activity) {
		Intent intent = new Intent(activity, CardRecoActivity.class);
		activity.startActivityForResult(intent, CardRecoActivity.msg_scan_bank_card);
	}

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scan_bank_card_activity_layout);
		ButterKnife.bind(this);
		check();
		initView();
		initTipMusic();
	}

	private void initView() {
		mOverlay.setmActivity(this);
		mFrameOrientation = ORIENTATION_LANDSCAPE_RIGHT;
		mCardScanner = new CardScanner(getApplicationContext(), this, mFrameOrientation, this);
		mCardScanner.prepareScanner();
		invalidateOverlapView();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (bCamera) {
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
			if (!restartPreview()) {
				CLog.e(TAG, "Could not connect to camera.");
				Toast.makeText(this, "ERROR_CAMERA_UNEXPECTED_FAIL", Toast.LENGTH_SHORT).show();
			} else {
			}
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mCardScanner != null) {
			mCardScanner.pauseScanning();
		}
	}

	@Override
	protected void onDestroy() {
		if (mCardScanner != null) {
			mCardScanner.endScanning();
			mCardScanner = null;
		}
		DictManager.getInstance().finishDict();
		super.onDestroy();
	}

	private boolean restartPreview() {
		CLog.d(TAG, "restartPreview()");
		boolean success = mCardScanner.resumeScanning(mSurfaceView.getHolder());
		return success;
	}

	public boolean isLowResolution() {
		return mCardScanner.isLowResolution();
	}


	/**
	 * 检查是否初始化扫描所必须的核心文件（字典）和授权
	 */
	private void check() {
		DictManager.getInstance().initDict(this, null);
		if (!DictManager.getInstance().hasInit()) {
			Toast.makeText(this, R.string.init_dict_failure_tip_of_expired_strs, Toast.LENGTH_SHORT).show();
			finish();
		}
	}


	/**
	 * 识别成功播放提示音乐并且振动
	 */
	private void playMusicAndVibrate() {
		if (playMusicFlag && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrateFlag) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(200);
		}
	}

	/**
	 * 初始化提示音
	 */
	private void initTipMusic() {
		if (playMusicFlag && mediaPlayer == null) {
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(playMusicListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}


	private final MediaPlayer.OnCompletionListener playMusicListener = new MediaPlayer.OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	@Override
	public void invalidateOverlapView() {
		CLog.d(TAG, "mFirstPreviewFrame");

		SurfaceView sv = mSurfaceView;
		int lft = sv.getLeft();
		int top = sv.getTop();
		int rgt = sv.getRight();
		int btm = sv.getBottom();

		mGuideFrame = mCardScanner.getGuideFrame();

		mGuideFrame.offset(lft, top);

		if (mOverlay != null) {
			mOverlay.setCameraPreviewRect(new Rect(lft, top, rgt, btm));
			mOverlay.invalidate();
		}
	}

	@Override
	public void getBankCardSuccess(EXBankCardInfo cardInfo) {
		CLog.i(TAG, "getBankCardSuccess");
		CLog.i(TAG, cardInfo.strNumbers + ">>>>>" + cardInfo.strBankName + ">>>" + cardInfo.strCardType);
		playMusicAndVibrate();
		Intent data = new Intent();
		data.putExtra(bank_card_number_flag, remove(cardInfo.strNumbers.trim(), ' '));
		setResult(RESULT_OK, data);
		finish();
	}

	private String remove(String resource, char ch) {
		StringBuffer buffer = new StringBuffer();
		int position = 0;
		char currentChar;

		while (position < resource.length()) {
			currentChar = resource.charAt(position++);
			if (currentChar != ch) buffer.append(currentChar);
		}
		return buffer.toString();
	}

	@OnClick(R.id.bankcard_scan_back_tv)
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.bankcard_scan_back_tv:
				finish();
				break;
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

}
